<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Article;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class ArticleController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid(): Grid
    {
        return Grid::make(new Article(), function (Grid $grid) {
            $grid->model()->orderByDesc('id');
            $grid->column('id');
            $grid->column('key')->display(function ($val) {
                return \App\Models\Article::ARTICLE_OPTIONS[$val];
            });
            $grid->column('title');
            $grid->column('sort');
            $grid->column('locale')->display(function ($var){
                return implode(',', $var);
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('key', '类型')->select(\App\Models\Article::ARTICLE_OPTIONS);
            });

            $grid->disableRowSelector();
            $grid->disableViewButton();
            $grid->showEditButton();
            $grid->createMode('default');
        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form(): Form
    {
        return Form::make(new Article(), function (Form $form) {
            $form->disableViewButton();
            $form->disableDeleteButton();


            $form->display('id');
            $form->select('key')->options(\App\Models\Article::ARTICLE_OPTIONS)->required();
            $form->text('title')->required();
            $form->image('image')->uniqueName();
            $form->editor('content')->required();
            $form->multipleSelect('locale')->options(config('app.locale_list'))->required();
            $form->number('sort')->default(0)->max(100);
            if($form->isCreating()){
                $form->hidden('page_views')->default(rand(10000,99999));
            }
            $form->saving(function (Form $form){
                $form->image = $form->input('image') ?: '';
            });
        });
    }
}
